Angular6 用户自定义标签开发

2018年4月23随着angular6 发布,我们可以看到在其官方手册中的模板元素章节中增加了一个Element 条目(中文),通过说明我们可以知道这个功能可以帮助我们将angular以html标签的形式嵌入到非angular的页面环境中。下面我们就通过一个简单的例子演示Angular6中的这一新功能。

新建angular工程

通过ng命令新建custom-tag工程

ng new custom-tag

cli新建完相应文件后会通过npm下载所信赖的包,完成后进入目录验证工作空间是否正常。

$cd custom-tag
$ng serve --open

--open参数的作用是直接打开浏览器,也可以通过浏览器中直接输入localhost:4200

angular.png

增加标签功能

修改app.component.html 内容

<!--The content below is only a placeholder and can be replaced.-->
<!--
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
  </li>
</ul>
-->
<input #inputtext type="text" placeholder="条目">
<input type="button" value="增加" (click)="addItem(inputtext.value)">
<ul>
    <li *ngFor="let item of items">{{item}}</li>
</ul>

为对应的类增加 addItem()方法,向类中的条目集合(items)增加用户输入的一个条目。

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  addItem(item:string){
    console.log(`${item} to be added!`);
    this.items.push(item);  
  }

  items:string[] =[];
}

小结

到目前为止这是一个普通的angular应用,通过增加按钮,要以向列表中增加元素。

应用状态

将完成内容转换为自定义标签

增加@angular/comonents信赖

$ng add @angular/elements

修改app.module.ts

从包中导入相关依赖:

import  { Injector} from '@angular/core';
import  { createCustomElement } from '@angular/elements';

将AppComponent改为动态组件,并通过createCustomElement()注册AppComponentcustom-items

import { BrowserModule } from '@angular/platform-browser';
import { NgModule,Injector } from '@angular/core';

import  { createCustomElement } from '@angular/elements';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  //bootstrap: [AppComponent]
  entryComponents :  [
    AppComponent
 ]
})
export class AppModule {
  constructor(private injector : Injector){
    const cust_tag = createCustomElement(AppComponent, {injector : this.injector});
    customElements.define('custom-items',cust_tag);
  }

  ngDoBootstrap() {}
 }

修改index.html页面

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>CustomTag</title>
    <base href="/">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
    <!--<app-root></app-root>-->
    <custom-items></custom-items>
</body>

</html>

页面重新出现在浏览器中了,功能也同先前一模一样。

由于浏览器版本的原因可能会出现下面错误,无法创建自定义标签

elements.js:384 Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
    at NgElementImpl.NgElement [as constructor] (elements.js:384)
    at new NgElementImpl (elements.js:420)
    at new AppModule (app.module.ts:24)
    at _createClass (core.js:8421)
    at _createProviderInstance (core.js:8393)
    at initNgModule (core.js:8326)
    at new NgModuleRef_ (core.js:9052)
    at createNgModuleRef (core.js:9041)
    at Object.debugCreateNgModuleRef [as createNgModuleRef] (core.js:10866)
    at NgModuleFactory_.push../node_modules/@angular/core/fesm5/core.js.NgModuleFactory_.create (core.js:11583)

可以通过修改tsconfig.json中的构建目标至es6解决该问题

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

增加外部事件

通过output 可以为自定义标签增加自定义事件

import { Component,Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  @Output() itemAdded:EventEmitter<string> = new EventEmitter<string>();
  addItem(item:string){
    console.log(`${item} to be added!`);
    this.items.push(item);  
    // 向外发送自定义事件
    this.itemAdded.emit(item);
  }

  items:string[] =[];
}

在客户端页面可以通过自定义标签对象的addEventListener()方法增加自定义事件响应,通过 event.detail可以获取到angular内部发送的内容

    <script>
        var items = document.querySelector('custom-items');

        items.addEventListener('itemAdded', (event) => {
            console.log(event);
        })
    </script>

完结与发布

在package.json中增加发布脚本

"scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build --prod --output-hashing none",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
    },

通过npm run build 执行构建,由于我们关闭了文件名hash,得到的输出目录内容如下:

liunan@liunan-desktop:~/webDev/custom-tag$ ls ./dist/custom-tag/
3rdpartylicenses.txt  favicon.ico  index.html  main.js  polyfills.js  runtime.js  scripts.js  styles.css

我们可以看到输出的index.html文件中采用如下方式引用了定义标签的输出,如果其他用户使用会非常不便,

<script type="text/javascript" src="runtime.js"></script>
<script type="text/javascript" src="polyfills.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript" src="main.js"></script>

我们可以通过使用cat命令将这些文件按照上面顺序合并成一个文件

$cat runtime.js polyfills.js scripts.js main.js > custom-items.js

这样用户就可以引用单个文件来使用我们制做的custom-items了。

一定注记合并文件的次序,需要严格按照上述次序进行,否则脚本可能不能正常工作。

示例代码

在线示例

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 近期我发现迷茫党还真不少,特别是刚毕业的学生尤为突出。工作两年,看惯了身边的人和事在不断变化着,有人留下,有人离开...
    咸鱼又萌阅读 187评论 0 0
  • 我上小学的时候是刚从乡下农村转到城里的,我父亲在政府机关谋到一份工作,我们全家就鲤鱼跃龙门都成为城里人了。 当我在...
    瓦全阅读 203评论 1 3
  • 充电宝 车充转换头 欧标插头 wifi电话卡 开国际漫游 驾照+翻译件 信用卡提额度 泳裤眼镜沙滩裤 蚊虫药
    shane911阅读 231评论 0 0